import {
  defineComponent,
  onMounted,
  ref,
  onBeforeUnmount,
  watch,
  nextTick,
} from 'vue'
import PropTypes from '@/utils/PropTypes'

import wangEditor from 'wangeditor'
export default defineComponent({
  name: 'MyEditor',
  props: {
    disabled: PropTypes.bool().def(false),
    content: PropTypes.string().def(''),
  },
  emits: ['update:getWangeditorText'],
  setup(props, { emit }) {
    console.log(props.content, 'props.content')

    const editortext = ref<string>(props.content)
    const editor = ref<any>()
    const wangEditorFunc = () => {
      editor.value = new wangEditor(`#div2`)
      editor.value.config.showLinkImg = false
      editor.value.config.height = 300
      // 配置菜单栏，设置不需要的菜单
      editor.value.config.excludeMenus = ['image', 'video']
      editor.value.config.uploadImgMaxSize = 3 * 1024 * 1024
      editor.value.config.customUploadImg = async function (
        resultFiles: any,
        insertImgFn: any,
      ) {
        // resultFiles 是 input 中选中的文件列表
        const formData = new FormData()
        resultFiles.forEach((item: any) => {
          formData.append('image', item)
        })
        // const data = await uploadImg(formData)
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        // 上传图片，返回结果，将图片插入到编辑器中
        // insertImgFn(data.data.image_url)
      }
      // 获取最新的 html 内容
      editor.value.config.onchange = function (newHtml: any) {
        editortext.value = newHtml
      }
      // 创建编辑器
      editor.value.create()
      editor.value.txt.clear()
      editor.value.txt.append(editortext.value)
      // editor = editor
    }
    onMounted(() => {
      wangEditorFunc()
    })
    watch(
      () => props.content,
      () => {
        nextTick(() => {
          editortext.value = props.content
          editor.value.txt.html(props.content)
        })
      },
    )
    watch(
      () => editortext.value,
      (val) => {
        emit('update:getWangeditorText', val)
      },
    )
    return () => (
      <div id="div2" style={{ position: 'relative', zIndex: 0 }}>
        <div v-model={editortext.value}></div>
      </div>
    )
  },
})
